package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Flight;

/**
 * Servlet implementation class AddToCart
 */
public class AddToCart extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddToCart() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}


	/**
	 * The doPost method gets the flight and cart from the session. The flight
	 * is added to the cart and the success message is returned.
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get session object
		HttpSession session = request.getSession();

		//Get the seat number
		int seatNum = Integer.parseInt(request.getParameter("seats"));

		//Get flight and add seat number to it
		Flight flight = (Flight) session.getAttribute("flight");
		flight.setSeats(seatNum);

		//Get shopping cart
		ArrayList<Flight> cart = (ArrayList<Flight>) session.getAttribute("shoppingCart");

		//Check if cart is empty
		if(cart == null){
			cart = new ArrayList<Flight>();
			cart.add(flight);
			session.setAttribute("shoppingCart", cart);
		} else {
			//Add flight and only add if it is a new flight number
			boolean toAdd = true;
			for(int i=0; i<cart.size(); i++){
				Flight temp = cart.get(i);
				if(temp.getId() == flight.getId()){
					toAdd = false;
				}
			}
			if(toAdd){
				cart.add(flight);
			}
		}	

		//Return that the flight was added
		response.getWriter().write("added");
	}

}
